package com.corpgovernment.organization.dataloader;

import com.corpgovernment.api.basic.bo.SearchByCityIdRequestBO;
import com.corpgovernment.api.basic.bo.SearchByCityIdResponseBO;
import com.corpgovernment.api.basic.dto.CtripAccountInfo;
import com.corpgovernment.api.basic.dto.MsgConfigInItDTO;
import com.corpgovernment.api.basic.request.CityInfoQuickDisplayRequest;
import com.corpgovernment.api.basic.response.CityInfoQuickDisplayResponse;
import com.corpgovernment.api.basic.soa.BasicClient;
import com.corpgovernment.api.basic.soa.BasicDataClient;
import com.corpgovernment.api.basic.soa.ChannelDataClient;
import com.corpgovernment.api.basic.vo.CityBasicInfoVO;
import com.corpgovernment.api.basic.vo.ProvinceInfoVO;
import com.corpgovernment.basicdata.bo.HotelCityBo;
import com.corpgovernment.common.base.JSONResult;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class BasicDataClientLoader {

	/**
	 * 常用国家
	 */
	public static final String COMMON_COUNTRY = "commonCountry";
	/**
	 * 省会城市
	 */
	public static final String CAPITAL_CITY = "capitalCity";
	/**
	 * 直辖市
	 */
	public static final String MUNICIPALITY_CITY = "municipalityCity";
	/**
	 * 计划单列市
	 */
	public static final String SPECIFICALLY_CITY = "specificallyCity";
	@Autowired
	private BasicDataClient basicDataClient;

	@Autowired
	private BasicClient basicClient;
	@Autowired
	private ChannelDataClient channelDataClient;


	/**
	 * 查询国内国际城市基础数据
	 * @return
	 */
	public CityInfoQuickDisplayResponse queryChineseCity(CityInfoQuickDisplayRequest request) {
		JSONResult<CityInfoQuickDisplayResponse> result = basicDataClient.getChineseCity( request);
		if (result == null || result.getData() == null) {
			log.error("查询国内国际城市基础数据接口异常:" + Optional.ofNullable(result).map(JSONResult::getMsg).orElse("接口无响应"));
			return null;
		}
		return result.getData();
	}

	/**
	 * 根据城市id获取基础城市信息
	 *
	 * @param cityIds
	 * @return
	 */
	public List<HotelCityBo> searchByCityIds(List<String> cityIds) {
		if (CollectionUtils.isEmpty(cityIds)) {
			return new ArrayList<>();
		}
		SearchByCityIdRequestBO request = new SearchByCityIdRequestBO();
		request.setCityIds(cityIds);
		JSONResult<SearchByCityIdResponseBO> result = basicDataClient.searchByCityIds(request);
		if (result == null || result.getData() == null) {
			log.error("获取基础城市信息异常:" + Optional.ofNullable(result).map(JSONResult::getMsg).orElse("接口无响应"));
			return new ArrayList<>();
		}
		return Optional.ofNullable(result.getData().getHotelCityList()).orElse(new ArrayList<>());
	}

	/**
	 * 查询国内城市基础数据 城市映射关系 安庆--安徽
	 * @return
	 */
	public Map<String,ProvinceInfoVO> batchQueryChinaCityMappingByName(List<String> names) {
		CityInfoQuickDisplayRequest requestInSea = new CityInfoQuickDisplayRequest();
		requestInSea.setForeignCity(false);
		requestInSea.setDisplayType(Arrays.asList(CAPITAL_CITY,MUNICIPALITY_CITY,SPECIFICALLY_CITY));
		CityInfoQuickDisplayResponse cityInfoInSeaDto = this.queryChineseCity(requestInSea);
		Map<String, List<CityBasicInfoVO>> cityMap = cityInfoInSeaDto.getCityInfoVO();

		// 国内省份匹配 上海--2 北京--1
		Map<String,String> provinceMap = cityInfoInSeaDto.getProvinceInfoVO().stream().filter(s -> s.getProvinceId() != null).collect(Collectors.toMap(data -> data.getProvinceId(), data -> data.getProvinceName(), (k, v) -> k));
		Map<String,ProvinceInfoVO> cityMappingProvince = new HashMap<>();
		for (String  key: cityMap.keySet()) {
			List<CityBasicInfoVO> item = cityMap.get(key);
			String provinceName = provinceMap.get(key);
			for (int i = 0; i < item.size(); i++) {
				CityBasicInfoVO item2 = item.get(i);
				ProvinceInfoVO provinceInfoVO = new ProvinceInfoVO(key,provinceName);
				cityMappingProvince.put(item2.getCityName(),provinceInfoVO);
			}
		}

		Map<String,ProvinceInfoVO> res = new HashMap<>();

		for (int i = 0; i < names.size(); i++) {
			res.put(names.get(i),cityMappingProvince.get(names.get(i)));
		}
		return res;
	}

	/**
	 * 查询国际城市基础数据 城市映射关系 中国--亚洲
	 * @return
	 */
	public Map<String,ProvinceInfoVO> batchQueryNotChinaCityMappingByName(List<String> names) {
		CityInfoQuickDisplayRequest requestOutSea = new CityInfoQuickDisplayRequest();
		requestOutSea.setForeignCity(true);
		requestOutSea.setDisplayType(Arrays.asList(COMMON_COUNTRY));
		CityInfoQuickDisplayResponse cityInfoInSeaDto = this.queryChineseCity(requestOutSea);
		Map<String, List<CityBasicInfoVO>> cityMap = cityInfoInSeaDto.getCityInfoVO();

		Map<String,String> provinceMap = cityInfoInSeaDto.getProvinceInfoVO().stream().filter(s -> s.getProvinceId() != null).collect(Collectors.toMap(data -> data.getProvinceName(), data -> data.getProvinceId(), (k, v) -> k));
		Map<String,ProvinceInfoVO> cityMappingProvince = new HashMap<>();
		for (String  key: cityMap.keySet()) {
			List<CityBasicInfoVO> item = cityMap.get(key);
			String provinceId = provinceMap.get(key);
			for (int i = 0; i < item.size(); i++) {
				CityBasicInfoVO item2 = item.get(i);
				ProvinceInfoVO provinceInfoVO = new ProvinceInfoVO(provinceId,key);
				cityMappingProvince.put(item2.getCityName(),provinceInfoVO);
			}
		}

		Map<String,ProvinceInfoVO> res = new HashMap<>();

		for (int i = 0; i < names.size(); i++) {
			res.put(names.get(i),cityMappingProvince.get(names.get(i)));
		}
		return res;
	}

	/**
	 * 获取appsecuriy
	 *
	 * @param corpId
	 * @param supplierCode
	 * @return
	 */
	public String getAppSecurity(String corpId, String supplierCode) {
		if (StringUtils.isBlank(corpId) || StringUtils.isBlank(supplierCode)) {
			return null;
		}
		JSONResult<String> result = basicDataClient.getAppSecurity(corpId, supplierCode);
		if (result == null || result.getData() == null) {
			log.error("获取AppSecurity异常:" + Optional.ofNullable(result).map(JSONResult::getMsg).orElse("接口无响应"));
			return null;
		}
		return result.getData();
	}

	/**
	 * 获取携程ticket
	 *
	 * @param corpId
	 * @param supplierCode
	 * @return
	 */
	public String ctripTokenByCorpID(String corpId, String supplierCode) {
		if (StringUtils.isBlank(corpId) || StringUtils.isBlank(supplierCode)) {
			return null;
		}
		JSONResult<String> result = basicDataClient.ctripTokenByCorpID(corpId, supplierCode);
		if (result == null || result.getData() == null) {
			log.error("获取携程ticket异常:" + Optional.ofNullable(result).map(JSONResult::getMsg).orElse("接口无响应"));
			return null;
		}
		return result.getData();
	}

	public CtripAccountInfo getCtripAccountInfo(){
		JSONResult<CtripAccountInfo> data = basicClient.getCtripAccountInfo();
		if (data == null || !data.isSUCCESS()){
			return null;
		}
		return data.getData();
	}

	public Boolean InitMsgSendConfig(String corpId) {
		if (StringUtils.isBlank(corpId)) {
			return Boolean.FALSE;
		}
		MsgConfigInItDTO request = new MsgConfigInItDTO();
		request.setCorpId(corpId);
		JSONResult<Boolean> result = channelDataClient.initOrgAllConfig(request);
		if (result == null || result.getData() == null) {
			log.error("初始化组织消息通知配置失败 :" + Optional.ofNullable(result).map(JSONResult::getMsg).orElse("接口无响应"));
			return Boolean.FALSE;
		}
		return result.getData();
	}

}